package com.lft.examsys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lft.examsys.entity.Item;
import com.lft.examsys.entity.Paper;
import com.lft.examsys.entity.User;
import com.lft.examsys.model.IModel;
import com.lft.examsys.service.ItemService;
import com.lft.examsys.service.PaperService;
import com.lft.examsys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/exam")
public class ExamController {

    @Autowired
    private PaperService paperService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private UserService userService;

    private static String pElName = "papers";
    private static String iElName = "items";

    @GetMapping("/result")
    @PreAuthorize("hasAnyAuthority('exam.result')")
    public ModelAndView result(IModel model) {
        return model.validation("/exam/result", () -> {
            User user = (User) model.user();
            List<Paper> paperList = userService.getRecentPapers(user.getId());
            model.add("papers", paperList);
        }, model::err);
    }

    @GetMapping()
    @PreAuthorize("hasAnyAuthority('exam.index')")
    public ModelAndView index(IModel model, Integer page, Integer size) {
        return model.validation("exam/papers", () -> {
            Page<Paper> pageInfo = new Page<>(page == null ? 1 : page, size == null ? 10 : size);
            Page<Paper> paperList = paperService.getAllOrderByTime(pageInfo);
            model.add("papers", paperList.getRecords());
            model.add("page", paperList.getCurrent());
            model.add("size", paperList.getSize());
            model.add("total", paperList.getPages());
            model.add("count", paperList.getTotal());
            Map<Object, Object> res = paperService.getPaperCount();
            model.add("itemsCount",res);
        }, model::err);
    }

    @PostMapping()
    @PreAuthorize("hasAnyAuthority('exam.submit')")
    public ModelAndView submit(IModel model, HttpServletRequest request) {
        return model.validation("exam/item", () -> {
            Map<String, String[]> map = request.getParameterMap();
            Integer paperId = Integer.parseInt(map.get("paperId")[0]);
            List<Integer> itemIds = new ArrayList<>();
            List<String> stringItemIds = Arrays.asList(map.get("itemId"));
            for (String id : stringItemIds) {
                itemIds.add(Integer.parseInt(id));
            }
            int sumScore = 100;
            int singleScore = sumScore/ itemIds.size();
            int getScore = 0;
            Map<Integer, List<String>> answer = new HashMap<>();
            for (String id : stringItemIds) {
                List<String> answers = Arrays.asList(map.get(id));
                Integer itemId = Integer.parseInt(id);
                answer.put(itemId,answers);
            }
            for (Integer itemId : itemIds) {
                if (itemService.checkAnswer(itemId,answer.get(itemId))) {
                    getScore += singleScore;
                }
            }
            Date localTime = new Date();
            User user = (User) model.user();
            if (paperService.insertScore(user.getId(), paperId, localTime, getScore)) {
                model.add("score", getScore);
            } else {
                model.err("插入中间表失败！");
            }
        }, model::err);
    }

    @GetMapping("/begin")
    @PreAuthorize("hasAnyAuthority('exam.begin')")
    public ModelAndView beginPaper(IModel model, Integer id, Integer page, Integer size) {
        return model.validation("exam/item", () -> {
            User user = (User) model.user();
            if (paperService.existExam(id, user.getId()) > 0) {
                Page<Paper> pageInfo = new Page<>(page == null ? 1 : page, size == null ? 10 : size);
                Page<Paper> paperList = paperService.getAllOrderByTime(pageInfo);
                model.add("papers", paperList.getRecords());
                model.add("page", paperList.getCurrent());
                model.add("size", paperList.getSize());
                model.add("total", paperList.getPages());
                model.add("count", paperList.getTotal());
                Map<Object, Object> res = paperService.getPaperCount();
                model.add("itemsCount",res);
                model.err("您已参加过改考试！不能重复考试");
                model.forwardTo("/exam/papers");
            } else {
                Paper paper = paperService.getPaperById(id);
                List<Item> itemList = itemService.getItemByPaperId(id);
                model.add("paper", paper);
                model.add("itemes", itemList);
            }
        }, model::err);
    }


}
